import axios, { type Method } from 'axios'
import { getLocalToken } from './auth'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

service.interceptors.request.use(
  config => {
    // 获取token
    const token = getLocalToken()
    // 有token则将它添加到请求头上
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error)
  },
)
const whiteList = ['/login']
service.interceptors.response.use(
  response => {
     
    return response.data
  },
  error => {
    // 如果状态码为401则让它跳转登录页面
    if (error.response.status === 401) {
      const router = useRouter()
      router.push('/login')
      // 2. 清空用户数据
      const store = useUserStore()
      store.clearUserInfo()
    }
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error)
  },
)

// 响应体的类型
type Data<T> = {
  code: number
  message: string
  data: T
}
// 4. 请求工具函数
const request = <T>(url: string, method: Method = 'get', submitData?: object) => {
  return service.request<T, Data<T>>({
    url,
    method,
    //判断如果是get请求，参数就是params，否则就是data
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}

export { request }
